import Vue from 'vue'
import Vuex from 'vuex'
import _ from 'lodash'
// import { post } from '../util/http'
Vue.use(Vuex)

/**
 * 构造菜单树
 * @param {object} parentNode 父菜单节点
 * @param {menus[]} allMenus 菜单数组
 */
const makeTree = (parentNode, allMenus) => {
  const children = _.filter(
    allMenus,
    o => {
      if ((_.isNil(o.parentId) || o.parentId === 'null' || o.parentId === '') && parentNode.id === 0) {
        return true
      }
      return o.parentId === parentNode.id && o.show
    }
  )
  _.forEach(children, function (child) {
    const node = {
      ...child,
      children: []
    }
    parentNode.children.push(node)
    makeTree(node, allMenus)
  })
}

// 构建父节点字段
const buildParentNode = (node, allMenus) => {
  let parent = allMenus.find(d => d.id === node.parentId)
  if (parent) {
    if (!parent.parents) {
      parent = buildParentNode(parent, allMenus)
    }
    node.parents = [...parent.parents, parent.menuName]
  } else {
    node.parents = []
  }
  return node
}

export default new Vuex.Store({
  state: {
    token: null, // TOKEN
    menus: [] // 菜单
  },
  mutations: {
    setToken (state, token) {
      state.token = token
    },
    setMenus (state, menus) {
      state.menus = menus
    }
  },
  getters: {
    menuTree (state) {
      // 菜单树
      let rootMenuNode = {
        id: 0,
        children: []
      }
      makeTree(rootMenuNode, state.menus)
      return rootMenuNode.children
    },
    menus (state) {
      return state.menus.map(d => {
        if (!d.parentId) {
          return d
        }
        return buildParentNode(d, state.menus)
      })
    },
    menuRoot (state) {
      // 根菜单
      return state.menus.filter(o => o.show && (_.isNil(o.parentId) || o.parentId === 'null' || o.parentId === '' || o.parentId === '0'))
    }
  },
  actions: {
    /**
     * 重新从服务器读取用户权限信息
     * @param {*} context store上下文
     */
    reloadUserAuthority (context) {
      // TODO 下面授权应该从后台接口获取 @ldy
      let menus = require('./menu.json')
      context.commit('setMenus', menus.map(d => {
        d.show = d.show !== false
        d.menuIcon = d.menuIcon || ''
        return d
      }))
    }
  },
  modules: {
  }
})
